/*
 * @Author: fu.lanyun 
 * @Date: 2019-03-07
 * @Desc: 流程处理
 */
import React from 'react';
import { Form, Input, Select, Modal, Button } from 'antd';
import { equals } from "@cbd/utils";
import { openNotificationWithIcon } from '../../utils/comm';

const { Option } = Select;
const { TextArea } = Input;

const formItemLayout1 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
const formItemLayout2 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 10 },
};

@Form.create()
class RollbackForm extends React.Component {

  state = {
    rollbackData: {},
  }

  openNotificationWithIcon = openNotificationWithIcon.bind(this);

  componentDidMount() {
    const { isView } = this.props;
    if (isView) {
      this.setFormValue();
      return;
    }
    this.initRollbackList();
  }

  componentDidUpdate(prevProps) {
    const { isView, data = {} } = this.props;
    if (isView && !equals(data, prevProps.data)) {
      this.setFormValue();
    }
  }

  setFormValue = () => {
    const { form, data = {} } = this.props;
    const { fromActivityName, toActivityName, comment } = data;
    form.setFieldsValue({
      currentActivityId: fromActivityName,
      newActivityId: toActivityName,
      comment,
    });
  }

  initRollbackList = () => {
    const { dispatch, data = {}, form } = this.props;
    const { taskId } = data || {};
    if (dispatch && taskId) {
      dispatch({ type: "FlowHandle/getRollbackList", payload: { taskId } }).then((res) => {
        const { errCode, errMsg, errortext, datas } = res || {};
        if (errCode === 0) {
          const { currentActivity = {} } = datas;
          form.setFieldsValue({ currentActivityId: currentActivity.name });
          this.setState({ rollbackData: datas });
          return;
        }
        this.openNotificationWithIcon('error', '', errMsg || errortext || '获取退回环节数据失败');
      });
    }
  }

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, dispatch } = this.props;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      const { rollbackData } = this.state;
      const { taskId, currentActivity = {} } = rollbackData;
      const { comment, newActivityId } = values;
      const params = { taskId, currentActivityId: currentActivity.id, comment, newActivityId };
      dispatch({ type: "FlowHandle/handleTaskRollback", payload: params }).then((data) => {
        const { errCode } = data;
        if (errCode === 0) {
          this.handleCancel(true);
          form.resetFields();
        }
      });
    });
  }

  handleCancel = (isQuery = false) => {
    const { onCancel } = this.props;
    if (onCancel) onCancel(false, '', isQuery);
  }

  renderFooter = (isView, confirmLoading) => {
    return (
      <div>
        <Button style={{ marginRight: 10 }} onClick={() => { this.handleCancel(false) }}>{`${isView ? '返回' : '取消'}`}</Button>
        {!isView && <Button loading={confirmLoading} type="primary" onClick={() => { this.handleOk() }}>提交</Button>}
      </div>
    )
  }

  render() {
    const { form, visible, title, disable = false, confirmLoading } = this.props;
    const { getFieldDecorator } = form;
    const { rollbackData } = this.state;
    const { newActivity = [] } = rollbackData;
    return (
      <Modal
        title={title || '退回'}
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => { this.handleCancel(false) }}
        footer={this.renderFooter(disable, confirmLoading)}
        width='582px'
        centered
        confirmLoading={confirmLoading}
      >
        <Form>
          <Form.Item
            label="当前环节"
            {...formItemLayout2}
          >
            {getFieldDecorator('currentActivityId', {})(
              <Input disabled placeholder='' />
            )}
          </Form.Item>
          <Form.Item
            label="退回至环节"
            {...formItemLayout2}
          >
            {getFieldDecorator('newActivityId', {
              // initialValue: '任务1',
              rules: [{ required: true, message: '请选择退回环节' }],
            })(
              <Select
                disabled={disable}
                placeholder="请选择退回至环节"
              >
                {newActivity.map(ele => <Option key={ele.id} value={ele.id}>{ele.name}</Option>)}
              </Select>
            )}
          </Form.Item>
          <Form.Item
            label="退回原因说明"
            {...formItemLayout1}
          >
            {getFieldDecorator('comment', {
              rules: [{ required: true, message: '请输入退回原因' }],
            })(
              <TextArea maxLength={500} placeholder="请输入退回原因" disabled={disable} rows={4} />
            )}
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}
export default RollbackForm;